'use strict';

var util = require('util');
var LifeCycle = require('./LifeCycle.js');
var mysql = require('mysql');
var redis = require('redis');
var http = require('http');
var debug = require('debug')('HttpServer');

function HttpServer(cfg) {
    this.cfg = cfg;
}
util.inherits(HttpServer, LifeCycle);
module.exports = HttpServer;

HttpServer.prototype.init = function (cb) {
    console.log('init');

    var self = this;
    var mysqlConn = mysql.createConnection(self.cfg.mysql);
    mysqlConn.connect(function (err) {
        if (err) return self.emit('error', err);
        console.log('connect mysql ok');
        var redisCli = redis.createClient(self.cfg.redis.port, self.cfg.redis.host);
        console.log('connect redis ok');
        self.__mysqlConn = mysqlConn;
        self.__redisCli = redisCli;
        process.nextTick(cb);
    });
};

HttpServer.prototype.start = function (cb) {
    console.log('start');
    var self = this;
    var server = http.createServer(self.__reqHandler.bind(self));
    server.on('error', function (err) {
        self.emit('error', err);
    });
    server.listen(self.cfg.http.port, function (err) {
        if (err) return self.emit('error', err);
        console.log('HttpServer start at port ' + self.cfg.http.port);
        cb();
    });
};

HttpServer.prototype.errorHandler = function (err) {
    console.log('errorHandler', err);
};

HttpServer.prototype.__reqHandler = function (req, res) {
    console.log('__reqHandler');
    console.log('receive request');
    var self = this;
    var sql = "select id,name,author,price from books limit 1";
    self.__mysqlConn.query(sql, function (err, rows, fields) {
        if (err) {
            res.end('server error');
            self.emit('mysql error:' + err);
            return;
        }

        var list = [];
        rows.forEach(function (item) {
            var obj = {
                id: item.id,
                name: item.name,
                author: item.author,
                price: item.price
            };
            list.push(obj);
        });
        console.log('from mysql, book[0]=' + JSON.stringify(list[0]));

        // after mysql done
        var book = list[0];
        self.__redisCli.hmset('book:' + book.id, "json", JSON.stringify(book), function (err) {
            if (err) {
                res.end('server error');
                self.emit('redis save err:' + err);
                return;
            }
            console.log('redis save done');

            // after redis done
            res.end(JSON.stringify(book) + '\n');
        });
    });
};